<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .bw {
            width: 400px;
            margin: 100px auto 0;
        }

        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
            width: 400px;
        }

        td {
            border: 1px solid #5513d16b;
            padding: 10px;
        }

        th {
            border: 1px solid #d0d0d0a8;
            background-color: rgb(0, 204, 0);
            color: #fff;
            padding: 10px;
        }

        tr {
            background-color: #f0f0f0;
        }
    </style>
</head>

<body>
    <div class="bw">
        <table>
            <tr>
                <th>
                    <input type="checkbox" id="contro1" />
                </th>
                <th>商品</th>
                <th>价格</th>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="fruit" />
                </td>
                <td>桃子</td>
                <td>15</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="fruit" />
                </td>
                <td>猕猴桃</td>
                <td>12</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="fruit" />
                </td>
                <td>香蕉</td>
                <td>11</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" class="fruit" />
                </td>
                <td>枸杞</td>
                <td>22</td>
            </tr>
        </table>
    </div>

    <script>
        // 需求1：实现全选和全不选的效果
        const ctrObj1 = document.querySelector("#contro1");
        const fruits = document.querySelectorAll(".fruit");

        ctrObj1.onclick = function () {
            //checked
            //当checkbox被选中的时候checked=true
            //当checkbox被取消选中的时候checked=false
            for (const ck of fruits) {
                ck.checked = this.checked;
            }
        }
        // 需求2：当所有元素被选中时，那么全选按钮也需要被选中
        for (const item of fruits) {
            item.onclick = function () {
                let flag = true;
                for (const ck of fruits) {
                    if (!ck.checked) {
                        flag = false;
                    }
                }
                ctrObj1.checked = flag;
            }
        }
    </script>

</body>

</html>